import { DirectiveBinding } from 'vue';


function draggable(el: HTMLElement, binding: DirectiveBinding) {
    let offsetX, offsetY;
    let initialLeft, initialTop;
    let isDragging = false;

    // 鼠标按下时开始拖拽
    el.addEventListener('mousedown', e => {
        e.stopPropagation()
        isDragging = true;
        offsetX = e.clientX - el.getBoundingClientRect().left;
        offsetY = e.clientY - el.getBoundingClientRect().top;
        initialLeft = el.offsetLeft;
        initialTop = el.offsetTop;
    });
    // 鼠标移动时拖动元素
    document.addEventListener('mousemove', e => {
        if (isDragging) {
            const left = e.clientX - offsetX;
            const top = e.clientY - offsetY;
            /*console.log('innerWidth',window.innerWidth)
            console.log('left',left)
            console.log('clientWidth',el.clientWidth)
            console.log('clientHeight',el.clientHeight)*/
            if((left+el.clientWidth+10)>window.innerWidth||(top+el.clientHeight+10)>window.innerHeight
            ||left<0||top<0
            ){
                return
            }
            el.style.left = `${left}px`;
            el.style.top = `${top}px`;
        }
    });

    // 鼠标松开时停止拖拽，并吸附到指定位置
    document.addEventListener('mouseup', (e) => {
        e.stopPropagation()
        if (isDragging) {
            isDragging = false;

            /*const containerWidth = el.parentElement.clientWidth;
            const elWidth = el.clientWidth;
            const snapThreshold = 20; // 吸附到左边或右边的阈值

            // 计算吸附到的位置
            if (el.offsetLeft < snapThreshold) {
                // 吸附到左边
                el.style.left = '0px';
            } else if (el.offsetLeft + elWidth > containerWidth - snapThreshold) {
                // 吸附到右边
                el.style.left = `${containerWidth - elWidth}px`;
            }*/
        }
    });
}

export default {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        draggable(el, binding);
    },
    updated(el: HTMLElement, binding: DirectiveBinding) {
        draggable(el, binding);
    },
};
